<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <title>滑块滑动</title>
    <style>
        ul {
            list-style: none;
            padding: 0;
            display: flex;
            justify-content: space-around;
        }

        a {
            text-decoration: none;
            color: black;
        }

        li a:hover {
            color: palevioletred;
        }

        .content {
            width: 300px;
            height: 500px;
            box-sizing: border-box;
            padding: 15px;
            background-color: antiquewhite;
        }
        .topbar{
            border-bottom: 1px solid black;

        }
        .line {
            width: 40px;
            height: 3px;
            background-color: palevioletred;
            transition: all 0.3s;
            transform: translate(9px);

        }

        .active {
            color: palevioletred;
        }
    </style>
</head>

<body>
    <div class="content">
        <div class="topbar">
            <ul>
                <li><a href="#" data-id="0" class="active">首页</a></li>
                <li><a href="#" data-id="1">音乐</a></li>
                <li><a href="#" data-id="2">动画</a></li>
                <li><a href="#" data-id="3">番剧</a></li>
                <li><a href="#" data-id="4">国创</a></li>

            </ul>
            <div class="line"></div>
        </div>

    </div>
    <script>
        const ul = document.querySelector('ul')
        // 事件监听ul点击事件
        ul.addEventListener('click', function (e) {
            // 点击的是链接,显示效果
            if (e.target.tagName === 'A') {
                // 获取点击对象id
                const i = +e.target.dataset.id
                // 点击后改变颜色
                document.querySelector('.active').classList.remove('active')
                document.querySelector(`li:nth-child(${i + 1}) a`).classList.add('active')
                // 滑块移动
                // document.querySelector('.line').style.transform = `translate(${6 + i * 55}px)`
                const n=e.target.offsetLeft
                document.querySelector('.line').style.transform = `translate(${n-25}px)`
            }

        })
    </script>
</body>

</html>